package com.acane.instagram.feature.friend

import android.annotation.SuppressLint
import android.util.Log
import android.widget.Toast
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Divider
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.ModalBottomSheetLayout
import androidx.compose.material.ModalBottomSheetState
import androidx.compose.material.ModalBottomSheetValue
import androidx.compose.material.rememberModalBottomSheetState
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavHostController
import coil.compose.AsyncImage
import com.acane.instagram.R
import com.acane.instagram.core.config.Config
import com.acane.instagram.core.design.theme.InstagramBlue
import com.acane.instagram.core.design.theme.InstagramDarkGray
import com.acane.instagram.core.design.theme.InstagramLightGray
import com.acane.instagram.core.model.UserInfo
import com.acane.instagram.feature.chat.CHAT_USER
import com.acane.instagram.feature.common.SessionManager
import com.acane.instagram.feature.login.LoginViewModel
import com.acane.instagram.feature.main.MAIN_ROUTE
import com.acane.instagram.feature.me.SwitchAccountDialog
import com.acane.instagram.viewmodel.ChatViewModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch


class ChatViewModelFactory(
    private val savedStateHandle: SavedStateHandle
) : ViewModelProvider.Factory {

    @Suppress("UNCHECKED_CAST")
    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        if (modelClass.isAssignableFrom(ChatViewModel::class.java)) {
            return ChatViewModel(savedStateHandle) as T
        }
        throw IllegalArgumentException("Unknown ViewModel class")
    }
}
@Composable
fun FriendRoute(
    navController: NavHostController,
    toChat: (String) -> Unit,
    toFriend: () -> Unit,
    toLogin: () -> Unit,
    toRegister: () -> Unit,
    toMain: () -> Unit,
) {
    // 使用 SavedStateHandle 传递参数给 ChatViewModel
    val savedStateHandle = remember { SavedStateHandle(mapOf(CHAT_USER to SessionManager.currentUser?.userName)) }
    val chatViewModel: ChatViewModel = viewModel(factory = ChatViewModelFactory(savedStateHandle))
    FriendScreen(
        navController = navController,
        toChat = toChat,
        toFriend = toFriend,
        toLogin = toLogin,
        chatViewModel = chatViewModel,
        toRegister = toRegister,
        toMain = toMain,
    )
}

@OptIn(ExperimentalMaterialApi::class)
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter", "StateFlowValueCalledInComposition")
@Composable
fun FriendScreen(
    chatViewModel: ChatViewModel,
    loginViewModel: LoginViewModel = viewModel(),
    navController: NavHostController,
    toChat: (String) -> Unit,
    toFriend: () -> Unit,
    toLogin: () ->Unit,
    friendViewModel: FriendViewModel = viewModel(),
    toRegister: () -> Unit,
    toMain: () -> Unit,
) {
    val context = LocalContext.current
    LaunchedEffect(key1 = Unit) {
        friendViewModel.loadData()
    }
    val messages by chatViewModel.messages.collectAsState()
    // 最新的消息
    val latestMessage: String = if (messages.isNotEmpty()) {
        messages.last().content
    } else {
        ""
    }
    Log.d("MessageItem", "🟢 获取到消息: $messages")
    Log.d("MessageItem", "🟢 最新消息: $latestMessage")

    val messageList: List<UserInfo> = friendViewModel.friendMessageList.value

    val accountListBottomSheetState = rememberModalBottomSheetState(initialValue = ModalBottomSheetValue.Hidden)

    val addAccountBottomSheetState = rememberModalBottomSheetState(initialValue = ModalBottomSheetValue.Hidden)
    val loggedAccountList = SessionManager.loggedAccountList

    val coroutineScope = rememberCoroutineScope()

    // 管理对话框的显示状态
    var showDialog by remember { mutableStateOf(false) }

    val userInfo = SessionManager.currentUser
    // 包裹两个 ModalBottomSheetLayout
    Box(modifier = Modifier.fillMaxSize()) {
        // 帐户列表抽屉布局
        ModalBottomSheetLayout(
            sheetState = accountListBottomSheetState,
            sheetShape = RoundedCornerShape(topStart = 10.dp, topEnd = 10.dp),
            sheetContent = {
                LazyColumn(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(top = 1.dp, bottom = 10.dp, start = 10.dp, end = 10.dp)
                ) {
                    // 添加 Bar
                    item {
                        Box(
                            modifier = Modifier
                                .fillMaxWidth()
                                .wrapContentSize(align = Alignment.Center)
                        ) {
                            Image(
                                painter = painterResource(id = R.drawable.bar_horizontal),
                                contentDescription = "bar",
                            )
                        }
                    }
                    // 主要内容区域
                    item {
                        Column(modifier = Modifier.padding(10.dp)) {
                            // 账户行
                            loggedAccountList.forEach { account ->
                                Row(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(vertical = 4.dp) // 添加垂直间距
                                ) {
                                    AsyncImage(
                                        model = account.avatar?.let {
                                            val url = "${Config.ADDRESS}avatars/$it"
                                            Log.d("MeRoute", "🟢 尝试加载头像 URL: $url")
                                            url
                                        },
                                        contentScale = ContentScale.Crop,
                                        contentDescription = "当前登录用户头像",
                                        modifier = Modifier
                                            .size(50.dp)
                                            .clip(CircleShape),
                                        error = painterResource(id = R.drawable.ic_default_avatar) // 加载失败时显示默认
                                    )
                                    // 用户名垂直居中
                                    account.userName?.let {
                                        Text(
                                            text = it,
                                            modifier = Modifier
                                                .align(Alignment.CenterVertically)
                                                .padding(start = 10.dp)
                                                .weight(1f)
                                        )
                                    }
                                    Image(
                                        painter = painterResource(if (account.userName == userInfo?.userName) R.drawable.circle_selected else R.drawable.circle_unselected),
                                        contentDescription = "accountList",
                                        modifier = Modifier
                                            .size(30.dp)
                                            .padding(start = 4.dp)
                                            .clip(CircleShape)
                                            .align(Alignment.CenterVertically)
                                            .clickable {
                                                //切换点击的账号
                                                coroutineScope.launch {
                                                    loginViewModel.login(
                                                        username = account.userName,
                                                        password = account.password,
                                                        toFriend = toFriend,
                                                    )
                                                    // 提示登录成功
                                                    Toast.makeText(context, "登录成功", Toast.LENGTH_SHORT).show()
                                                    accountListBottomSheetState.hide()
                                                }
                                            }
                                    )
                                }
                            }
                            // 固定的一行
                            Row(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(top = 10.dp)
                            ) {
                                Image(
                                    painter = painterResource(id = R.drawable.circle_plus),
                                    contentDescription = "addAccount",
                                    modifier = Modifier
                                        .size(50.dp)
                                        .clip(CircleShape)
                                        .clickable {
                                            //弹出底部抽屉
                                            coroutineScope.launch {
                                                //关闭上一个抽屉
                                                accountListBottomSheetState.hide()
                                                addAccountBottomSheetState.show()
                                            }
                                            Log.d("ProfilePage", "addAccount clicked")
                                        }
                                )
                                Text(
                                    text = "添加账户",
                                    modifier = Modifier
                                        .align(Alignment.CenterVertically)
                                        .padding(start = 10.dp)
                                )
                            }
                        }
                    }
                }
            }
        ) {
            Scaffold(
                topBar = {
                    userInfo?.let {
                        FriendBar(
                            userInfo = it,
                            navController = navController,
                            coroutineScope = coroutineScope,
                            accountListBottomSheetState = accountListBottomSheetState,
                        )
                    }
                },
                containerColor = Color.White
            ) { paddingValues ->
                Column(
                    modifier = Modifier.padding(paddingValues)
                ) {
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.Center,
                        verticalAlignment = Alignment.CenterVertically,
                    ) {
                    //搜索框跳转按钮
                    Button(
                        onClick = {
                            //navController.navigate("search_detail")
                        },
                        colors = ButtonDefaults.buttonColors(
                            containerColor = InstagramLightGray,
                            contentColor = Color.Black
                        ),
                        modifier = Modifier
                            .height(35.dp)
                            .width(380.dp),
                        shape = RoundedCornerShape(5.dp),
                        elevation = ButtonDefaults.buttonElevation(defaultElevation = 0.dp),
                        contentPadding = PaddingValues(horizontal = 10.dp, vertical = 0.dp) // 设置内容内边距
                    ) {
                        Row(
                            modifier = Modifier.fillMaxWidth(),
                            horizontalArrangement = Arrangement.Start, // 使内容靠左对齐
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Icon(
                                painter = painterResource(id = R.drawable.search), // 替换为你的搜索图标资源ID
                                contentDescription = "Search Icon",
                                tint = MaterialTheme.colorScheme.onSurface,
                                modifier = Modifier.size(15.dp)
                            )
                            Spacer(modifier = Modifier.width(10.dp))
                            Text(
                                text = "搜索",
                                fontSize = 12.sp,
                                color = InstagramDarkGray
                            )
                        }
                    }
                        }
                    Spacer(modifier = Modifier.height(10.dp))
                    Row(
                        horizontalArrangement = Arrangement.Center,
                        verticalAlignment = Alignment.CenterVertically,
                    ) {
                        Spacer(modifier = Modifier.width(15.dp))
                        Text(
                            text = "消息",
                            color = Color.Black,
                            fontSize = 16.sp,
                            fontWeight = FontWeight.Bold
                        )
                        Spacer(modifier = Modifier.weight(1f))
                        Text(
                            text = "陌生消息",
                            color = InstagramBlue,
                            fontSize = 16.sp,
                            fontWeight = FontWeight.Bold,
                            modifier = Modifier.padding(end = 15.dp)
                        )
                    }
                    if (messageList.isNotEmpty()) {
                        LazyColumn {
                            items(messageList, key = { it.id ?: "" }) { message ->
                                MessageItem(
                                    message = message,
                                    toChat = toChat,
                                    latestMessage = latestMessage,
                                )
                            }
                        }
                    } else {
                        // 如果 messageList 为空，显示一个提示信息
                        LazyColumn {
                            item {
                                Text(text = "暂无消息")
                            }
                        }
                    }

                }
            }
        }
    }
    //添加帐户的抽屉
    ModalBottomSheetLayout(
        sheetState = addAccountBottomSheetState,
        sheetShape = RoundedCornerShape(topStart = 10.dp, topEnd = 10.dp),
        sheetContent = {
            Column(
                verticalArrangement = Arrangement.Center,
                horizontalAlignment = Alignment.CenterHorizontally,
            ) {
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .wrapContentSize(align = Alignment.Center)
                ) {
                    Image(
                        painter = painterResource(id = R.drawable.bar_horizontal),
                        contentDescription = "bar",
                    )
                }
                Text(text = "添加帐户")
                // 分割线
                Divider(modifier = Modifier
                    .fillMaxWidth()
                    .padding(vertical = 15.dp))
                Button(
                    onClick = {
                        coroutineScope.launch {
                            //关闭上一个抽屉
                            addAccountBottomSheetState.hide()
                            //打开Dialog
                            showDialog = true
                        }
                    },
                    colors = ButtonDefaults.buttonColors(
                        containerColor = InstagramBlue,
                        contentColor = Color.White
                    ),
                    modifier = Modifier
                        .height(60.dp)
                        .padding(horizontal = 8.dp)
                        .fillMaxWidth(),
                    shape = RoundedCornerShape(5.dp),
                    elevation = ButtonDefaults.buttonElevation(defaultElevation = 0.dp),
                    contentPadding = PaddingValues(horizontal = 8.dp, vertical = 0.dp)
                ) {
                    Text(
                        text = "登录现有帐户",
                        fontSize = 16.sp,
                        color = Color.White,
                        fontWeight = FontWeight.Bold
                    )
                }
                Spacer(modifier = Modifier.height(10.dp))
                Text(
                    text = "新建帐户",
                    color = InstagramBlue,
                    fontSize = 14.sp,
                    fontWeight = FontWeight.Bold,
                    modifier = Modifier
                        .padding(bottom = 20.dp)
                        .clickable { }
                )
            }
        }
    ) { }
    // 根据 showDialog 状态显示对话框
    if (showDialog) {
        SwitchAccountDialog(
            toLogin = toLogin,
            onDismissRequest = { showDialog = false },
            loggedAccountList = loggedAccountList,
            toRegister = toRegister,
            toMain = toMain,
        )
    }






}

@Composable
fun MessageItem(
    message: UserInfo,
    toChat: (String) -> Unit,
    latestMessage: String? = null,
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 15.dp, vertical = 8.dp)
            .clickable {
                toChat(message.userName!!)
            },
        verticalAlignment = Alignment.CenterVertically
    ) {
        // 头像
        AsyncImage(
            model = message.avatar?.let {
                val url = "${Config.ADDRESS}avatars/$it"
                Log.d("MeRoute", "🟢 尝试加载头像 URL: $url")
                url
            },
            contentScale = ContentScale.Crop,
            contentDescription = "用户头像",
            modifier = Modifier
                .size(50.dp)
                .clip(CircleShape),
            error = painterResource(id = R.drawable.ic_default_avatar) // 加载失败时显示默认
        )
        Spacer(modifier = Modifier.width(10.dp))
        Column(
            modifier = Modifier
                .weight(1f)
                .padding(end = 8.dp)
        ) {
            // 昵称
            Text(
                text = message.nickName ?: message.userName ?: "未知用户",
                fontSize = 16.sp,
                fontWeight = FontWeight.Bold,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis,
            )

            if (latestMessage != null) {
                Text(
                    text = latestMessage,
                    fontSize = 14.sp,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis,
                )
            }
        }
    }

}

@OptIn(ExperimentalMaterial3Api::class, ExperimentalMaterialApi::class)
@Composable
fun FriendBar(
    userInfo: UserInfo,
    navController: NavHostController,
    coroutineScope: CoroutineScope,
    accountListBottomSheetState: ModalBottomSheetState,
) {
    TopAppBar(
        colors = TopAppBarDefaults.topAppBarColors(
            containerColor = Color.White
        ),
        title = {},
        navigationIcon = {
            Row(
                modifier = Modifier.padding(end = 8.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                androidx.wear.compose.material3.IconButton(
                    onClick = {
                        navController.popBackStack()
                        navController.navigate(MAIN_ROUTE) {
                            popUpTo(MAIN_ROUTE) { inclusive = true }
                            // 添加刷新参数
                            launchSingleTop = true
                            restoreState = false
                            anim {
                                //enter = R.anim.fade_in
                                exit = R.anim.fade_out
                            }
                        }
                    },
                    modifier = Modifier
                        .size(45.dp)
                        .padding(start = 10.dp, end = 10.dp)
                ) {
                    Image(
                        painter = painterResource(id = R.drawable.arrow_left),
                        contentDescription = "back",
                        modifier = Modifier
                            .size(30.dp)
                    )
                }
                userInfo.userName?.let {
                    Text(
                        text = it,
                        fontWeight = FontWeight.Bold,
                        fontSize = 20.sp,
                        modifier = Modifier.padding(top = 10.dp, start = 10.dp)
                    )
                }
                androidx.wear.compose.material3.IconButton(
                    onClick = {
                        // 显示底部抽屉
                        coroutineScope.launch {
                            accountListBottomSheetState.show()
                            Log.d("MeRoute", "accountListBottomSheetState.show()")
                        }
                    },
                    modifier = Modifier
                        .size(30.dp)
                        .padding(start = 10.dp, top = 10.dp)
                ) {
                    Image(
                        painter = painterResource(id = R.drawable.arrow_down),
                        contentDescription = "account"
                    )
                }
            }
        },
    )
}
